package cn.edu.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.time.LocalDate;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Mr.ma
 * @since 2022/11/23 10:14
 **/
public class JwtUtil {
    private static final String SIGN = "mdq";

    /**
     * 创建token令牌
     * @param params token令牌中存储的自定义信息
     * @return
     */
    public static String createToken(Map<String,Object> params){
        Map<String,Object> head=new HashMap<>(4);
        head.put("alg","HS256");
        head.put("typ","JWT");
        Date iss = new Date();

        Calendar nowTime = Calendar.getInstance();
        nowTime.add(Calendar.MINUTE,30);
        Date expire = nowTime.getTime();

        String token = JWT.create()
                .withHeader(head)
                .withExpiresAt(expire)
                .withIssuedAt(iss)
                .withIssuer("Mr.ma")
                .withClaim("userInfo",params)
                .sign(Algorithm.HMAC256(SIGN));
        return token;
    }

    /**
     * 校验token字符串是否合法，使用SIGN签名等信息生成校验对象，对token进行校验
     * @param token
     * @return
     */
    public static boolean verifyToken(String token) {
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(SIGN)).build();
        try {
            DecodedJWT verify = jwtVerifier.verify(token);
            return true;
        } catch (JWTVerificationException e) {
            System.out.println("token令牌无效");
            return false;
        }
    }

    /**
     * 解析token字符串，将令牌中的自定义信息转换成集合对象
     * @param token
     * @return
     */
    public static Map<String, Object> decodeJWT(String token) {
        Map<String, Object> userInfo = JWT.decode(token).getClaim("userInfo").asMap();
        return userInfo;
    }


    public static void main(String[] args) {
        Map<String,Object> map = new HashMap<>(6);
        map.put("username","张三");
        map.put("age",18);
        map.put("address","北京朝阳区");
        String token = createToken(map);
        System.out.println("token = " + token);

        Map<String, Object> userMap = decodeJWT(token);
        System.out.println("userMap = " + userMap);
        boolean b = verifyToken(token);
        System.out.println("b = " + b);
    }
}
